package com.webamc.util;

import com.webamc.dao.IKeyDao;
import com.webamc.dao.db4o.KeyDao;
import com.webamc.model.KeyBean;

/**
 * Created by Prash.
 * User: Choti
 * Date: Mar 29, 2009
 * Time: 2:39:28 PM
 * To change this template use File | Settings | File Templates.
 */
public class KeyUtil {
    private static KeyUtil keyUtil;
    private static IKeyDao keyDao;
    private static KeyBean k;

    private KeyUtil() {
    }

    public static KeyUtil instance() {
        if (null == keyUtil) {
            synchronized (KeyUtil.class) {
                if (null == keyUtil) {
                    keyUtil = new KeyUtil();
                    keyDao = new KeyDao(); //TODO: Apply Spring IOC
                    k = keyDao.getKeyBean(); //try fetch from DB

                    if (k == null) {
                        k = new KeyBean();
                        keyUtil.saveKeys();
                    }
                }
            }
        }

        return keyUtil;
    }

    public synchronized void saveKeys() {
        keyDao.saveKeyBean(k);
    }

    public synchronized int getNextAmcId() {
        incrAmcId();
        saveKeys();
        return k.getAmcId();
    }

    public synchronized int getNextAmcOrderId() {
        incrAmcOrderId();
        saveKeys();
        return k.getAmcOrderId();
    }

    public synchronized int getNextProductId() {
        incrProductId();
        saveKeys();
        return k.getProductId();
    }

    public synchronized int getNextProductOrderId() {
        incrProductOrderId();
        saveKeys();
        return k.getProductOrderId();
    }

    public synchronized int getNextCustomerId() {
        incrCustomerId();
        saveKeys();
        return k.getCustomerId();
    }

    public synchronized int getNextUserId() {
        incrUserId();
        saveKeys();
        return k.getUserId();
    }

    public synchronized int getNextAmcTaskId() {
        incrAmcTaskId();
        saveKeys();
        return k.getAmcTaskId();
    }

    private void incrAmcId() {
        k.setAmcId(k.getAmcId() + 1);
    }

    private void incrAmcOrderId() {
        k.setAmcOrderId(k.getAmcOrderId() + 1);
    }

    private void incrProductId() {
        k.setProductId(k.getProductId() + 1);
    }

    private void incrProductOrderId() {
        k.setProductOrderId(k.getProductOrderId() + 1);
    }

    private void incrCustomerId() {
        k.setCustomerId(k.getCustomerId() + 1);
    }

    private void incrUserId() {
        k.setUserId(k.getUserId() + 1);
    }

    private void incrAmcTaskId() {
        k.setAmcTaskId(k.getAmcTaskId() + 1);
    }
}
